package cn.easybuy.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONObject;

import cn.easybuy.utils.EmptyUtils;
import cn.easybuy.utils.PrintUtil;
import cn.easybuy.utils.ReturnResult;

import java.lang.reflect.Executable;
import java.lang.reflect.Method;
import java.sql.SQLException;


/**
 * 	抽象类
 * 	公共的 Servlet 类
 * @author Jerry
 *
 */

public abstract class AbstractServlet extends HttpServlet {

	
	public abstract Class getServletClass();
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		this.doPost(req, resp);
	}

	
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		String actionIndicator = req.getParameter("action");
		
		Method method = null;
		Object result = null;
		
		try {
			if (EmptyUtils.isEmpty(actionIndicator)) {
				req.getRequestDispatcher("/pre/index.jsp").forward(req, resp);
			} else {
				method = getServletClass().getDeclaredMethod(actionIndicator, HttpServletRequest.class,HttpServletResponse.class);
				result = method.invoke(this, req,resp);	
			}
			toView(req,resp,result);
		} catch (NoSuchMethodException e) {
			String viewName = "404.jsp";
			req.getRequestDispatcher(viewName).forward(req, resp);
		} 
		catch (Exception e) {
			e.printStackTrace();
			if (!EmptyUtils.isEmpty(result)) {
				if (result instanceof String) {
					String viewName = "500.jsp";
					req.getRequestDispatcher(viewName).forward(req, resp);
				} else {
					ReturnResult returnResult = new ReturnResult();
					returnResult.returnFail("系统错误");
					PrintUtil.write(returnResult,resp);
				}
			} else {
				String viewName = "500.jsp";
				req.getRequestDispatcher(viewName).forward(req, resp);
			}
		}
	}
	
	
	protected void toView(HttpServletRequest req, HttpServletResponse resp,Object result) throws ServletException, IOException{
		if (!EmptyUtils.isEmpty(result)) {
			if (result instanceof String) {
				String viewName = result.toString()+".jsp";
				req.getRequestDispatcher(viewName).forward(req, resp);
			} else {
				PrintUtil.write(result,resp);
			}
		}
	}
	
	
	
	public void write(Object obj,HttpServletResponse response) {
		response.setCharacterEncoding("text/html;charset=UTF-8");
		String json = JSONObject.toJSONString(obj);
		PrintWriter writer = null;
		if (null != response) {
			try {
				writer = response.getWriter();
				writer.print(json);
				writer.flush();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				writer.close();
			}
		}
	}
}